package com.xyrl.project.common.base.service.impl;

import com.xyrl.common.base.exception.RedisConnectException;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.common.util.domain.RedisInfo;
import com.xyrl.project.common.base.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Redis 工具类，只封装了几个常用的 redis 命令，
 * 可根据实际需要按类似的方式扩展即可。
 *
 * @author MrBird
 */
@Service("redisService")
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static String separator = System.getProperty("line.separator");

    @Override
    public List<RedisInfo> getRedisInfo() throws RedisConnectException {
        List<RedisInfo> infoList = new ArrayList<>();
        Properties properties = redisTemplate.getConnectionFactory().getConnection().info();
        if (ObjectUtil.isNotEmpty(properties)) {
            for (Object key : properties.keySet()) {
                RedisInfo redisInfo = new RedisInfo();
                redisInfo.setKey(key + "");
                redisInfo.setValue(properties.get(key) + "");
                infoList.add(redisInfo);
            }
        }
        return infoList;
    }

    @Override
    public Map<String, Object> getKeysSize() throws RedisConnectException {

        Long dbSize = redisTemplate.getConnectionFactory().getConnection().dbSize();
        Map<String, Object> map = new HashMap<>();
        map.put("create_time", System.currentTimeMillis());
        map.put("dbSize", dbSize);


        return map;
    }

    @Override
    public Map<String, Object> getMemoryInfo() throws RedisConnectException {
        Map<String, Object> map = null;
        Properties properties = redisTemplate.getConnectionFactory().getConnection().info();
        if (ObjectUtil.isNotEmpty(properties)) {
            map = new HashMap<>();
            map.put("used_memory", properties.get("used_memory"));
            map.put("create_time", System.currentTimeMillis());
        }
        return map;
    }

}
